﻿using Ducu.SRV.ServiceInteface;
using Ducu.SRV.ViewModel;
using Ducu.SRV.ViewModel.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Ducu.UI.Responsible.Controllers
{
    public class RegisterController : BaseController
    {
        #region Constructor

        private IRegisterService _registerSevice;
        private ILogService _logService;
        public RegisterController(IRegisterService registerService, ILogService logService)
        {
            _registerSevice = registerService;
            _logService = logService;
        }

        #endregion

        #region URL: /Register

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Index(RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            //encode the UserName
            model.UserName = Server.HtmlEncode(model.UserName);

            //check whether the username is exist by its password            
            if (_registerSevice.IsUserNameExist(model.UserName))
            {
                ModelState.AddModelError("UserName", "*用户名已被使用");
                return View(model);
            }

            _registerSevice.Do(model);
            _logService.On(new OnModel
            {
                UserName = model.UserName,
                Password = model.Password
            }, null);

            string nextUrl = "/Profile/Edit";
            if (!string.IsNullOrEmpty(Prepage.GetFromUrl()))
            {
                nextUrl += ("?prepage=" + Prepage.GetFromUrl());
            }

            return Redirect(nextUrl);
        }

        #endregion

    }
}